
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"

#include "../ArchiveWriter.h"
#include "../ArchiveReader.h"
#include <list>
#include <vector>
#include <iostream>
#include <fstream>
#include <assert.h>

// test extract all files
TEST(LibarchiveWapperReaderTest, testExtractTo)
{
	bool ret = false;
	ArchiveReader reader1("test_compress.zip");
	ret = reader1.extractTo("test_compress");
	ASSERT_TRUE(ret == true);

	ret = reader1.extractTo("C:/Windows/Temp");
	ASSERT_TRUE(ret == true);
}

// test extract special file
TEST(LibarchiveWapperReaderTest, testExtractFileTo)
{
	// test_compress.zip contains 'test1/test1.txt' and 'test2.txt'
	bool ret = false;
	ArchiveReader reader1("test_compress.zip");
	ret = reader1.extractTo("test2.txt", "testExtractFileTo");
	ASSERT_TRUE(ret == true);

	ret = reader1.extractTo("test/test1.txt", "testExtractFileTo");
	ASSERT_TRUE(ret == true);
}

// test extract file one by one
TEST(LibarchiveWapperReaderTest, testExtractNext)
{
	//suppose more than one file
	bool ret = false;
	ArchiveReader reader1("test_compress.zip");
	ret = reader1.extractNext("test_compress");
	ASSERT_TRUE(ret == true);

	ret = reader1.extractNext("C:/Windows/Temp");
	ASSERT_TRUE(ret == true);

	int32_t errCode = reader1.getLastErrorCode();
	ASSERT_TRUE(errCode == 0);

	ret = reader1.extractNext("C:/Windows/Temp2");
	ASSERT_TRUE(ret == false);

	errCode = reader1.getLastErrorCode();
	ASSERT_TRUE(errCode != 0);
}

// test extract file content
TEST(LibarchiveWapperReaderTest, testExtractNext2)
{
	std::ifstream iff ("test_compress.zip", std::ios::binary);
	iff.seekg(0, std::ios::end);
	size_t size = iff.tellg();
	iff.seekg(0, std::ios::beg);
	std::vector<unsigned char> ff(size);
	char buf[1024] = { 0 };

	while (iff.good())
	{
		iff.read((char*)&*ff.begin(), size);
	}
	std::copy((char*)&*ff.begin(), (char*)&*ff.begin() + size, buf);

	ArchiveReader reader(std::move(ff));
	std::pair<std::string, std::vector<unsigned char>> data = reader.extractNext();

	ASSERT_TRUE(data.first.length() > 0);

	ArchiveReader reader1((unsigned char*)buf, size);
	std::pair<std::string, std::vector<unsigned char>> data1 = reader1.extractNext();
	ASSERT_TRUE(data1.first.length() > 0);
}

